﻿using MediatR;
using NPOI.SS.Formula.Functions;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 获取采购/委外订单
    /// </summary>
    public class SearchPurchaseOutsourceHandler : IRequestHandler<SearchPurchaseOutsourceCommand, Result<PageResultDto<PurchaseOutsourcesDto>>>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPurchaseOutsourceHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public SearchPurchaseOutsourceHandler(ISqlSugarClient db, ILogger<SearchPurchaseOutsourceHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 获取采购/委外订单信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<PurchaseOutsourcesDto>>> Handle(SearchPurchaseOutsourceCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PurchaseOutsourcesDto>>() { Code = (int)CommonErrorCode.Search };
            //实例化分页
            var page = new PageResultDto<PurchaseOutsourcesDto>() { TotalCount = 0, PageCount = 0, List = new List<PurchaseOutsourcesDto>() };
            try
            {
                //总条数
                RefAsync<int> totalCount = 0;
                //总页数
                RefAsync<int> totalPage = 0;
                //六表联查
                var query = _db.Queryable<PurchaseOutsources, PurchaseType, AffiliatedProject, Currency, Suppliers, Departments>((p, t, a, c, s, d) => p.PurchaseTypeId == t.PurchaseTypeId && p.AffiliatedProjectId == a.AffiliatedProjectId && p.CurrencyId == c.CurrencyId && p.SupplierId == s.SupplierId && p.DepartmentId == d.DepartmentId)
                    .Select((p, t, a, c, s, d) => new PurchaseOutsourcesDto()
                    {
                        PurchaseId = p.PurchaseId,   
                        PurchaseNumber = p.PurchaseNumber,
                        PurchaseName = p.PurchaseName,
                        PurchaseTypeId = p.PurchaseTypeId,
                        AffiliatedProjectId = p.AffiliatedProjectId,
                        ProtocolCoding = p.ProtocolCoding,
                        ProtocolName = p.ProtocolName,
                        PurchaseNote = p.PurchaseNote,
                        SupplierId = p.SupplierId,
                        CurrencyId = p.CurrencyId,
                        PaymentAmount = p.PaymentAmount,
                        StartTime = p.StartTime,
                        EndTime = p.EndTime,
                        TheDateOfSigning = p.TheDateOfSigning,
                        PurchaseStatus = p.PurchaseStatus,
                        TaxType = p.TaxType,
                        TaxRate = p.TaxRate,
                        PreparedBy = p.PreparedBy,
                        DepartmentId = p.DepartmentId,
                        CreatedOwner = p.CreatedOwner,
                        CreatedTime = p.CreatedTime,
                        UpdateOwner = p.UpdateOwner,
                        UpdateTime = p.UpdateTime,
                        ExamineOwner = p.ExamineOwner,
                        ExamineTime = p.ExamineTime,
                        ApprovalStatus = p.ApprovalStatus,
                        AffiliatedProjectName = a.AffiliatedProjectName,
                        PurchaseTypeName = t.PurchaseTypeName,
                        CurrencyName = c.CurrencyName,
                        SupplierName = s.SupplierName,
                        DepartmentName = d.DepartmentName,
                    });
                //订单编码模糊查
                if (!string.IsNullOrEmpty(request.PurchaseNumber))
                {
                    query = query.Where(p => p.PurchaseNumber.Contains(request.PurchaseNumber));
                }
                //订单名称模糊查
                if (!string.IsNullOrEmpty(request.PurchaseName))
                {
                    query = query.Where(p => p.PurchaseName.Contains(request.PurchaseName));
                }
                //订单类型精确查
                if (request.PurchaseTypeId != 0)
                {
                    query = query.Where(p => p.PurchaseTypeId == request.PurchaseTypeId);
                }
                //供应商精确查
                if (request.SupplierId != 0)
                {
                    query = query.Where(p => p.SupplierId == request.SupplierId);
                }
                //项目精确查
                if (request.AffiliatedProjectId != 0)
                {
                    query = query.Where(p => p.AffiliatedProjectId == request.AffiliatedProjectId);
                }
                //状态精确查
                if (request.PurchaseStatus != 0)
                {
                    query = query.Where(p => p.PurchaseStatus == request.PurchaseStatus);
                }
                //分页
                var list = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                //总条数
                page.TotalCount = totalCount;
                //总页数
                page.PageCount = totalPage;
                //显示
                page.List = list;
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取采购/委外订单信息显示成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取采购/委外订单信息显示异常" + ex.Message;
                _logger.LogError("获取采购/委外订单信息显示异常" + ex.Message);
            }
            return result;
        }
    }
}
